package org.ezplatform.office.meeting.task.web.rest;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.ezplatform.cloud.api.component.popuser.PopUserScopeUtilService;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.pagination.PropertyFilter;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.controller.BaseController;
import org.ezplatform.core.web.util.WebUtils;
import org.ezplatform.core.web.view.OperationResult;
import org.ezplatform.mobile.util.common.service.CommonService;
import org.ezplatform.office.meeting.common.util.MeetingSendMsgUtils;
import org.ezplatform.office.meeting.common.util.MeetingUtils;
import org.ezplatform.office.meeting.info.entity.ApplyRecord;
import org.ezplatform.office.meeting.info.service.ApplyRecordService;
import org.ezplatform.office.meeting.task.entity.MeetingTaskInfo;
import org.ezplatform.office.meeting.task.service.MeetingTaskInfoService;
import org.ezplatform.util.DateUtils;
import org.ezplatform.util.StringUtils;
import org.ezplatform.util.UuidUtils;
import org.ezplatform.util.ValidateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName: MeetingTaskInfoController
 * @Description: 会议申请记录控制类
 */
@RestController
@RequestMapping(value = "/api/w/taskInfoController")
public class MeetingTaskInfoWebApiController extends BaseController<MeetingTaskInfo, String> {

	@Autowired
	private MeetingTaskInfoService meetingTaskInfoService;
	
	@Autowired
	private PopUserScopeUtilService popUserScopeUtilService;
	
	@Autowired
	private MeetingUtils meetingUtils;
	
	@Autowired
	private MeetingSendMsgUtils meetingSendMsgUtils;
	
	@Autowired
	private ApplyRecordService applyRecordService;
	
	@Autowired
	private CommonService commonService;
	
	@Override
	protected BaseService<MeetingTaskInfo, String> getEntityService() {
		return meetingTaskInfoService;
	}
	
	/**
	 * 初始化数据
	 * @param request
	 * @param model
	 * @param id
	 */
	@ModelAttribute
	public void prepareModel(HttpServletRequest request, Model model,
			@RequestParam(value = "id", required = false) String id) {
		super.initPrepareModel(request, model, id);
	}

	@RequestMapping(value = "/entityIsExist", method = RequestMethod.POST)
	public OperationResult entityIsExist(String id) {
		MeetingTaskInfo entity = this.meetingTaskInfoService.findOne(id);
		if(entity == null) return OperationResult.buildSuccessResult("notExist");
		else return OperationResult.buildSuccessResult("exist");
	}
	
	/**
	 * 根据会议id获取任务列表
	 * @param request
	 * @return
	 */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Page<Map> findTaskList(HttpServletRequest request) {
    	String applyrecordId = request.getParameter("applyrecordId");
    	String endTime = ValidateUtils.filter(request.getParameter("endTime"));
    	String userName = ValidateUtils.filter(request.getParameter("userName"));
    	WebUser user = WebUtils.getCurrentUser();
    	String corpId = user.getCorpId();
    	Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(request);
		List<PropertyFilter> buildFilters = PropertyFilter.buildFiltersFromHttpRequest(MeetingTaskInfo.class, request);
		Page<Map> page = this.meetingTaskInfoService.findTaskInfoByPage(pageable, buildFilters, applyrecordId, endTime, corpId, userName);
		return page;
    }
    
    /**
	 * 根据用户获取任务列表
	 * @param request
	 * @return
	 */
    @RequestMapping(value = "/mineList", method = RequestMethod.GET)
    public Page<Map> findMineTaskList(HttpServletRequest request) {
    	String status = ValidateUtils.filter(request.getParameter("status"));
    	String meetingName = ValidateUtils.filter(request.getParameter("meetingName"));
    	String startTime = ValidateUtils.filter(request.getParameter("startTime"));
    	String endTime = ValidateUtils.filter(request.getParameter("endTime"));
    	WebUser user = WebUtils.getCurrentUser();
    	String corpId = user.getCorpId();
    	String userId = user.getUserId();
    	Pageable pageable = PropertyFilter.buildPageableFromHttpRequest(request);
		List<PropertyFilter> buildFilters = PropertyFilter.buildFiltersFromHttpRequest(MeetingTaskInfo.class, request);
		Page<Map> page = this.meetingTaskInfoService.findMineTasksByPage(pageable, buildFilters, userId, corpId, status, meetingName, startTime, endTime);
		return page;
    }
    
    /**
     * 根据用户获取超期任务数量
     * @param request
     * @return
     */
    @RequestMapping(value = "/expiredTasksCount", method = RequestMethod.GET)
    public int expiredTasksCount(HttpServletRequest request) {
    	WebUser user = WebUtils.getCurrentUser();
    	String corpId = user.getCorpId();
    	String userId = user.getUserId();
    	return this.meetingTaskInfoService.taskInfosCount("0", "", userId, corpId, "");
    }
    
    /**
     * 保存/修改
     *
     * @param entity
     * @param model
     * @return
     */
    @RequestMapping(value = "/editSave", method = RequestMethod.POST)
    public OperationResult editSave(@ModelAttribute("entity") MeetingTaskInfo entity, Model model,HttpServletRequest request) {
    	Map failureMap = new HashMap();
    	WebUser user = WebUtils.getCurrentUser();
    	String applyRecordId = entity.getApplyRecordId();
    	String title = entity.getTitle();
    	String id = StringUtils.null2String(entity.getId());
    	MeetingTaskInfo taskInfo = this.meetingTaskInfoService.findTaskByTitle(applyRecordId, title);
		if(taskInfo != null){
			if(StringUtils.isEmpty(id) || !taskInfo.getId().equals(id)){
				failureMap.put("i18NCode", "oa.meeting.tip20");
				return OperationResult.buildFailureResult("同一会议下的任务标题不能重复",failureMap);
			}
		}
    	// 主持人
        String resUserJsonStr = StringUtils.null2String(request.getParameter("jsonStrResponseUser"));
        String resUser = StringUtils.null2String(entity.getResponseUser());
        if ("".equals(resUser)) {
        	resUser = UuidUtils.UUID();
            entity.setResponseUser(resUser);
        }
        this.popUserScopeUtilService.saveScopeData("oa_meeting_apply_record_scope", resUser, resUserJsonStr, "oa_meeting_task_info", "response_user");
        OperationResult result = super.editSave(entity);
        //if(StringUtils.isEmpty(id)){
			Map<String, Object> ds = new HashMap<>();
			String corpId = WebUtils.getCurrentUser().getCorpId();
			ApplyRecord applyRecord = this.applyRecordService.findOne(applyRecordId);
			ds.put("type", 6);
			ds.put("applyRecordId", applyRecordId);
			ds.put("meetingName", applyRecord.getName());
			Date date = entity.getEndTime();
			ds.put("endTime", DateUtils.formatDate(date, "yyyy年MM月dd日"));
			ds.put("title", entity.getTitle());
			ds.put("id", entity.getId());
			ds.put("userId", user.getUserId());
			ds.put("userName", user.getCnName());
			ds.put("userOrg", user.getOrgId());
			Map<String, String> idsMap = new HashMap<>();
			idsMap = this.transformUserScopePlatform2Dd(resUser, "oa_meeting_task_info", "response_user", corpId, TOKEN);
			String resUserId = idsMap.get("ids");
			String jsonIds = "[" + idsMap.get("jsonIds");
			if(!StringUtils.isEmpty(resUserId)){
				boolean mobilePush = false;
	            boolean emailPush = false;
	            boolean smsPublish = false;
				String mesgPush = applyRecord.getMessagePush();
				if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("mobile")) mobilePush = true;
				if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("email")) emailPush = true;
				if(StringUtils.isNotEmpty(mesgPush) && mesgPush.contains("sms")) smsPublish = true;
				resUserId = resUserId.substring(0, resUserId.length()-1);
				ds.put("userIds", resUserId);
				ds.put("orgIds", "");
				this.meetingSendMsgUtils.sendMail(ds, emailPush, corpId, TOKEN);
				this.meetingSendMsgUtils.sendMsgToApp(ds, mobilePush, corpId, TOKEN, request);
				this.meetingSendMsgUtils.sendSMS(ds, smsPublish, corpId, TOKEN);
			}
			if(StringUtils.isNotEmpty(jsonIds)){
				jsonIds = jsonIds.substring(0, jsonIds.length()-1);
				jsonIds += "]";
				this.meetingSendMsgUtils.sendMessage(ds, jsonIds, corpId, TOKEN);
			}
		//}
        return result;
    }
    
    private Map<String, String> transformUserScopePlatform2Dd(String fieldDataValue, String table, String fieldData, String corpId, String token){
        String ids = "", jsonIds = "";
		Map<String, String> result = new HashMap<>();
        String scopeTypeStr = this.popUserScopeUtilService.getScopeTypeValue("oa_meeting_apply_record_scope", table, fieldData, StringUtils.null2String(fieldDataValue));
        String[] scopeTypeArray = scopeTypeStr.split(",");
        if(scopeTypeArray != null && scopeTypeArray.length>0) {
            for (int i = 0; i < scopeTypeArray.length; i++) {
                String[] info = scopeTypeArray[i].split("SCOPE");
                if (info.length > 1){
                    String id  = info[1];
					jsonIds +="{\"10\":\""+id+"\"},";
					ids += id + ",";
//                    List<String> l = this.userApiService.getUserIdBySysOrThird(id, "1", "DD", corpId, token);
//                    if(l!=null && l.size()>0){
//                    	ids += l.get(0) + ",";
//                    }
                }
            }
        }
		result.put("jsonIds", jsonIds);
		result.put("ids", ids);
		return result;
    }
    
    /**
     * 改变任务进度
     * @param request
     * @return
     */
    @RequestMapping(value = "/changeProgress", method = RequestMethod.POST)
    public OperationResult changeProgress(HttpServletRequest request) {
    	String progress = StringUtils.null2String(request.getParameter("progress"));
    	String comDetails = StringUtils.null2String(request.getParameter("comDetails"));
    	String id = StringUtils.null2String(request.getParameter("id"));
    	this.meetingTaskInfoService.updateProgress(Integer.parseInt(progress), id);
    	this.meetingTaskInfoService.updateDetails(comDetails, id);
    	return OperationResult.buildSuccessResult("保存成功");
    }
    
    /**
     * 完成任务
     * @param request
     * @return
     */
    @RequestMapping(value = "/complete", method = RequestMethod.POST)
    public OperationResult complete(@RequestParam("ids") String... ids) {
    	int count = this.meetingTaskInfoService.updateProgress(100 , ids);
    	if(count > 0) return OperationResult.buildSuccessResult("保存成功");
    	else return OperationResult.buildFailureResult("保存失败");
    }
    
    /**
     * 编辑页面
     * 
     * @param model
     * @return
     */
    @RequestMapping(value = "/editShow", method = RequestMethod.GET)
    public Map<String, Object> editShow(HttpServletRequest request) {
        WebUser user = WebUtils.getCurrentUser();
        String corpId = user.getCorpId();
        String id = StringUtils.null2String(request.getParameter("id"));
        Map<String, Object> result = new HashMap<>();
        String editType = request.getParameter("editType");
        MeetingTaskInfo info = new MeetingTaskInfo();
        if (StringUtils.isNotEmpty(id)) {
            info = this.meetingTaskInfoService.findOne(id);
            result.put("entity", info);

            // 负责人
            /*result.put("responseUser", info.getResponseUser());
            result.put("responseUserName", "");*/
            if("view".equals(editType)){
            	if(info == null) {
            		result.put("entityIsDelete", true);
            		return result;
            	}
				String responseUser = this.popUserScopeUtilService.getScopeTypeValue("oa_meeting_apply_record_scope", "oa_meeting_task_info", "response_user", StringUtils.null2String(info.getResponseUser()));
            	if(StringUtils.isNotEmpty(responseUser)) {
//                  String scopeName = this.userApiService.getScopeName(responseUser, corpId, TOKEN);
                	String scopeName = applyRecordService.getScopeName("oa_meeting_task_info", info.getResponseUser(), "response_user");
                    result.put("responseUserName", scopeName);
                }
            	String createdUser = info.getCreatedBy();
            	String createdUserName = "";
            	result.put("isCreatedUser", false);
            	if(createdUser.equals(user.getUserId())){
            		createdUserName = user.getCnName();
            		result.put("isCreatedUser", true);
            	}else{
//            		Map<String, Object> userMap = this.userApiService.getUser(createdUser, corpId, "", TOKEN);
//            		if(CollectionUtils.isNotEmpty(userMap)){
//            			createdUserName = StringUtils.null2String(userMap.get("userName"));
//            		}
            		createdUserName = applyRecordService.getUserNameById(createdUser);
            	}
            	result.put("createdUserName", createdUserName);
            	result.put("entityIsDelete", false);
            }
        }else{
        	//当前日期
            String hidApplyRecordDate = DateUtils.formatDate(DateUtils.now());
            result.put("hidApplyRecordDate", hidApplyRecordDate);
        }
        
        //会议所有参与人
        String applyRecordId = StringUtils.null2String(request.getParameter("applyRecordId"));
        if(StringUtils.isNotEmpty(id)){
        	applyRecordId = info.getApplyRecordId();
        }
    	ApplyRecord applyRecord = this.applyRecordService.findOne(applyRecordId);
    	/*List<String> list = this.applyRecordService.getApplyRecordUserList(applyRecord, TOKEN);
    	String userIds = "";
    	if(list!=null && list.size()>0){
    		for (String uId : list) {
				if(uId != null){
					userIds += uId + ",";
				}
			}
    		if(!"".equals(userIds)){
    			userIds = userIds.substring(0,userIds.length()-1);
    		}
    	}*/
    	List<String> list = this.applyRecordService.getApplyRecordAttendPeopleList(applyRecord, TOKEN);
    	String limitData = "";
    	if(list != null && list.size() > 0){
    		for (String uId : list) {
				if(uId != null){
					limitData += uId + ",";
				}
			}
    		if(!"".equals(limitData)){
    			limitData = limitData.substring(0, limitData.length()-1);
    		}
    	}
    	result.put("limitData", limitData);

        // 查询基础设置
//        String noticeType = "";
//        BaseSet baseSet = this.baseSetService.getBaseSetInfo(corpId);
//        if (baseSet != null) {
//            noticeType = baseSet.getNoticeType();
//        }
        String noticeType = commonService.getSysParamValueByMark(corpId, TOKEN,"sysImType");
        result.put("noticeType", noticeType);
        return result;
    }
    
    /**
     * 删除（批量）数据
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public OperationResult delete(@RequestParam("ids") String... ids) {
    	WebUser user = WebUtils.getCurrentUser();
        String corpId = user.getCorpId();
    	//删除相关任务消息
    	this.meetingSendMsgUtils.deleteMessage(Arrays.asList(ids), corpId, TOKEN);
        return super.delete(ids);
    }
    
}
